--[[日志类 用于输出打印
]]
local M = {}

ISPRINT = true
local function getPrintPosInfo()
	local source = debug.getinfo(3, "S")
	local line = debug.getinfo(3, "l")

	local info = "-------- " .. string.sub(source.source, -30) .. "  line:" .. line.currentline ..  " --------"

	return info
end

-- 正常的打印
function M.print(...)
	if not ISPRINT then
		return
	end

	local info = getPrintPosInfo()

	print(info)

	print(...)
	
	print(info)
end

-- warning 级别
function M.warning(...)
	if not ISPRINT then
		return
	end

	local params = {...}
	
	local info = getPrintPosInfo()

	print(info)

	print("warning: ")
	for k, v in pairs(params) do
		if type(v) == "table" then
			print(json.prettify(v))
		else
			print(v)
		end
	end
	
	print(info)
end

-- error 级别
function M.error(...)
	if not ISPRINT then
		return
	end

	local params = {...}

	local info = getPrintPosInfo()

	print(info)
	print("error: ")
	for k, v in pairs(params) do
		if type(v) == "table" then
			print(json.prettify(v))
		else
			print(v)
		end
	end
	
	print(info)
end

-- 打印调用堆栈
function M.printStack()
	if not ISPRINT then
		return
	end

	local info = getPrintPosInfo()

	print(info)

	print(debug.traceback())
	
	print(info)
end

local function formatPrintTable(ta)
	if type(ta)=="string" and json.decode(ta) then
		ta = json.decode( ta )
	end
	if type(ta)~="table" then
		print( ta )
		return
	end

	local function getValue( v )
		return type(v)=="string" and '"'..v..'"' or tostring(v)
	end

	local function getKey( k )
		if tonumber(k) and type(k)=="string" then
			return "["..k.."] = "
		elseif type(k)=="string" then
			return k.." = "
		else
			return ""
		end
	end

	local function getList( tc )
		local list = "{ "
		for k,v in pairs(tc) do
			if type(k)~="number" or type(v)=="table" then return end
			list = list..getValue(v)..( k==#tc and " }," or ", " )
		end
		return list
	end

	local tCache = {}
	local function printTable( tb, lv )
		local indent = string.rep( "\t", lv )

		for k,v in pairs(tb) do
			local key = getKey(k)
			if type(v)=="table" and not tCache[tostring(v)] then
				tCache[tostring(v)] = true
				if next(v) then
					local list = getList(v)
					if list then
						print( indent..key..list )
					else
						print( indent..key.."{" )
						printTable( v, lv+1 )
					end
				else
					print( indent..key.."{}," )
				end
			else
				print( indent..key..getValue(v).."," )
			end
		end

		indent = string.rep( "\t", lv-1 )
		print( indent..( lv==1 and "}" or "}," ) )
	end

	print( "{" )
	printTable( ta, 1 )
end
-- 将 json字符串 或 lua的table，打印为mod中的数据形式
function M.printT( ... )
	if not ISPRINT then
		return
	end
	
	local info = getPrintPosInfo()
	print(info)
	for k, v in pairs({...}) do
		if type(v) == "string" then
			local tInfo = json.decode(v)
			if tInfo then
				formatPrintTable(tInfo)
			else
				print(v)
			end
		else
			formatPrintTable(v)
		end
	end
	print(info)
end

return M